<template>
  <el-dialog
    :title="!dataForm.brandId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <!--注意@keyup.enter.native是一个回车触发，就是把回车看成是提交-->
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="140px"
    >
      <el-form-item label="品牌名" prop="name">
        <el-input v-model="dataForm.name" placeholder="品牌名"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo地址" prop="logo">
        <singleupload v-model="dataForm.logo"></singleupload>
      </el-form-item>
      <el-form-item label="介绍" prop="descript">
        <el-input v-model="dataForm.descript" placeholder="介绍"></el-input>
      </el-form-item>
      <el-form-item label="显示状态" prop="showStatus">
        <el-switch
          v-model="dataForm.showStatus"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item label="检索首字母" prop="firstLetter">
        <el-input
          v-model="dataForm.firstLetter"
          placeholder="检索首字母"
        ></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model.number="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dataFormCancel()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
// 导入已经集成好的
import singleUpload from "../../mall/components/upload/singleUpload.vue";
import { brandInfo, brandSave, brandUpdate } from "@/api/mall/brand";
import { ossSingleDelete } from "@/api/mall/thirdparty";
export default {
  components: { singleupload: singleUpload },
  data() {
    return {
      visible: false,
      dataForm: {
        brandId: 0,
        name: "",
        logo: "",
        descript: "",
        showStatus: 1,
        firstLetter: "",
        sort: 0,
      },
      dataRule: {
        name: [{ required: true, message: "品牌名不能为空", trigger: "blur" }],
        logo: [
          { required: true, message: "品牌logo地址不能为空", trigger: "blur" },
        ],
        descript: [
          { required: true, message: "介绍不能为空", trigger: "blur" },
        ],
        showStatus: [
          {
            required: true,
            message: "显示状态[0-不显示；1-显示]不能为空",
            trigger: "blur",
          },
        ],
        firstLetter: [
          {
            // 使用validator声明规则，直接用箭头函数在这里声明规则。
            // 需要接收三个参数，rule(用不到),value(就是这个input输入的内容),callback(成败的回调方法，接收Error输入)
            validator: (rule, value, callback) => {
              // 如果输入空值
              if (value == "") {
                // 返回提示
                callback(new Error("检索首字母必须填写"));
                // 用正则表达式匹配是否是英文字母，取反
              } else if (!/^[a-zA-Z]$/.test(value)) {
                callback(new Error("检索首字母必须是英文字母"));
              } else {
                // 符合要求，回调函数无输入
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        sort: [
          {
            validator: (rule, value, callback) => {
              // 如果输入空值
              if (value == null) {
                // 返回提示
                callback(new Error("排序必须填写"));
              } else if (!Number.isInteger(value) || value < 0) {
                callback(new Error("排序必须是大于等于0的整数"));
              } else {
                // 符合要求，回调函数无输入
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    init(id) {
      this.dataForm.brandId = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.brandId) {
          brandInfo(this.dataForm.brandId).then((data) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.brand.name;
              this.dataForm.logo = data.brand.logo;
              this.dataForm.descript = data.brand.descript;
              this.dataForm.showStatus = data.brand.showStatus;
              this.dataForm.firstLetter = data.brand.firstLetter;
              this.dataForm.sort = data.brand.sort;
            }
          });
        }
      });
    },
    // 关闭表单
    // 只有add情况下关闭表单才需要删除OSS中对应的文件
    // 这样防止在update关闭表单，却删除了OSS文件
    dataFormCancel() {
      if (!this.dataForm.brandId) {
        // 只把域名之后的内容提取出来
        var fileName = this.dataForm.logo.substr(
          this.dataForm.logo.lastIndexOf(".com/") + 5
        );
      }
      var filejson = { fileName: fileName };
      ossSingleDelete(filejson).then(({ data }) => {});
      this.visible = false;
    },

    // 表单提交
    // 如果是update还需要删除旧的OSS文件
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          var json = {
            brandId: this.dataForm.brandId || undefined,
            name: this.dataForm.name,
            logo: this.dataForm.logo,
            descript: this.dataForm.descript,
            showStatus: this.dataForm.showStatus,
            firstLetter: this.dataForm.firstLetter,
            sort: this.dataForm.sort,
          };
          if (!this.dataForm.brandId) {
            brandSave(json).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          } else {
            brandUpdate(json).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        }
      });
    },
  },
};
</script>